<template>
<el-scrollbar>
  <el-menu class="menu" 
   background-color="#001529"
   text-color="#a6adb4"
   active-text-color="#c8b2f4"
   :collapse-transition="false"
   :collapse="isCollapse"
   router>
      <template v-for="(item,index) in menuList" :key="item.path">
         <el-menu-item  v-if="item.children == null" :index="item.path">
            <SvgIcon :name="item.icon" />
            <template #title>{{item.title}}</template>
         </el-menu-item>

         <el-submenu v-else :index="item.path">
            <template #title>
               <SvgIcon :name="item.icon" />
               <span>{{item.title}}</span>
            </template>

            <el-menu-item  v-for="child in item.children" :key="child.path" :index="child.path">
               {{child.title}}
            </el-menu-item>
         </el-submenu>
      </template>
     
  </el-menu>
</el-scrollbar>
  
</template>

<script>
import {computed, reactive} from 'vue'
import { useStore } from 'vuex'
import {useRouter} from 'vue-router'

const generateMenu = (routes)=>{
   let menuList;
   menuList = routes.filter(item => {
      if(item.noShow == null || item.noShow == false){
         return true
      }
      return false;
   })

   menuList = menuList.map(item => {
      if(item.children.length == 1){
         const childItem = item.children[0]
         if(item.path == '/'){
            item.path = ''
         }
         return {
            path: item.path+'/'+childItem.path,
            icon: childItem.meta.icon,
            title: childItem.meta.title
         }
      }else if(item.children.length > 1){
         
         const childItems = item.children

         const children = childItems.map(child => {
            return{
               path: item.path+'/'+child.path,
               title: child.meta.title
            }
         })

         return {
            path: item.path,
            icon: item.meta.icon,
            title: item.meta.title,
            children: children
         }
      }
   })
   return menuList
}

export default {
    setup(){
       //处理收缩菜单
       const {state} = useStore()
       const isCollapse = computed(() => {
          return  state.menu.isCollaspe
       })
   
       //如果要配合后台使用权限，应从vuex中获取动态的路由表
       const {routes} = useRouter().options
       const menuList = reactive(generateMenu(routes)) 
       
      // {path: "/dashboard", icon: "yibiaopan", title: "仪表盘"}
       return{
          isCollapse,menuList
       }
    }
}
</script>

<style>

</style>